package com.aoip.telemetry.telemetry.core.util;

import org.springframework.util.StringUtils;

/**
 * 数组，集合，字符串转换工具类
 *
 * @author chenbai
 * @version 1.0
 * @date 2022/3/11 16:12
 */
public class ArrayTransferUtil {


    /**
     * 将整形数组转，按照指定分隔符转换成字符串。
     * eg input int[] ints = {11,22,33}; String separator = ",";
     * output 11,22,33
     *
     * @param ints      待转换整形数组
     * @param separator 指定分隔符
     * @return java.lang.String
     * @author chenbai
     * @date 2022/3/11
     **/
    public static String array2Int(int[] ints, String separator) {
        if (ints == null || ints.length < 1) {
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (int value : ints) {
            stringBuilder.append(value).append(",");
        }
        String string = stringBuilder.toString();
        if (string.endsWith(separator)) {
            string = string.substring(0, string.length() - 1);
        }
        return string;
    }

    /**
     * 根据字符串转换成整形数组
     * eg input String string = "11,22,33"; String separator = ",";
     * output int[] ints = {11,22,33};
     *
     * @param string    待转换字符串
     * @param separator 字符串分隔符
     * @return int[]
     * @author chenbai
     * @date 2022/3/11
     **/
    public static int[] string2Array(String string, String separator) {
        if (!StringUtils.hasText(string)) {
            return new int[0];
        }
        String[] split = string.split(separator);
        int[] ints = new int[split.length];
        for (int i = 0; i < split.length; i++) {
            ints[i] = Integer.valueOf(split[i]);
        }
        return ints;
    }

}
